<script setup>
import { ref, defineEmits, defineProps, onMounted } from "vue"
import request from '@/api/request'
import { ElMessage } from 'element-plus'
import { useRouter } from "vue-router"

let router = useRouter()
let emits = defineEmits(["ref-table"])
let props = defineProps(["data1"])
let data = ref()

// 自动生成功能相关
const autoGenerate = ref(false)

let Process = ref([])
let select = () => {
  request({
    url: '/processStep/Name',
    method: 'get'
  }).then(res => {
    Process.value = res.data
  })
}
select()

let Workshop = ref([])
let select1 = () => {
  request({
    url: '/workstation/Name',
    method: 'get'
  }).then(res => {
    Workshop.value = res.data
  })
}
select1()

// 生成工作站编码
const generateWorkstationId = () => {
  const now = new Date()
  const year = now.getFullYear().toString().substr(2) // 取年份后两位
  const month = (now.getMonth() + 1).toString().padStart(2, '0')
  const day = now.getDate().toString().padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  return `WK${year}${month}${day}${random}`
}

// 处理自动生成功能开关
const handleAutoGenerate = (val) => {
  if (val) {
    // 开启自动生成
    workstation.value.workstationId = generateWorkstationId()
  } else {
    // 关闭自动生成，清空编码
    workstation.value.workstationId = ''
  }
}

// 重新生成编码
const regenerateCode = () => {
  if (autoGenerate.value) {
    workstation.value.workstationId = generateWorkstationId()
  }
}

let onSubmit = () => {
  // 表单验证
  if (!workstation.value.workstationId) {
    ElMessage.warning('工作站编号不能为空')
    return
  }
  
  if (!workstation.value.workstationName) {
    ElMessage.warning('工作站名称不能为空')
    return
  }
  
  if (!workstation.value.workshopId) {
    ElMessage.warning('请选择所在车间')
    return
  }
  
  if (!workstation.value.processId) {
    ElMessage.warning('请选择所属工序')
    return
  }
  
  request({
    url: '/workstation/insert',
    method: 'post',
    data: {
      ...workstation.value,
    }
  }).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message || res.data)
    } else {
      ElMessage.success('添加成功')
      emits("ref-table")
      // 如果开启自动生成，成功后生成新的编码
      if (autoGenerate.value) {
        workstation.value.workstationId = generateWorkstationId()
        // 其他字段重置
        workstation.value.workstationName = ''
        workstation.value.workstationLocation = ''
        workstation.value.workshopId = ''
        workstation.value.processId = ''
        workstation.value.isEnabled = '0'
        workstation.value.remark = ''
      }
    }
  }).catch(error => {
    ElMessage.error('请求失败: ' + error.message)
  })
}

let workstation = ref({
  workstationId: '',
  workstationName: '',
  workstationLocation: '',
  workshopId: '',
  processId: '',
  isEnabled: '0' // 默认启用
})

// 组件挂载时如果开启自动生成则生成编码
onMounted(() => {
  if (autoGenerate.value) {
    generateWorkstationId()
  }
})
</script>

<template>
  <div>
    <el-card>
      <template #header>
        <el-form :model="workstation" style="padding-left: 70px;" class="card_wrap">
          <el-form-item label="工作站编号" class="c_item_big">
            <div style="display: flex; align-items: center;">
              <el-input 
                v-model="workstation.workstationId" 
                style="width: 350px;"
                :readonly="autoGenerate"
                placeholder="请输入工作站编号"
              ></el-input>
              <el-switch 
                v-model="autoGenerate"
                active-text="自动生成"
                @change="handleAutoGenerate"
                style="margin-left: 15px;"
              />
              <el-button 
                v-if="autoGenerate"
                @click="regenerateCode"
                style="margin-left: 10px;"
                size="small"
              >
                重新生成
              </el-button>
            </div>
          </el-form-item>
          
          <el-form-item label="工作站名称" class="c_item_big">
            <el-input 
              v-model="workstation.workstationName" 
              style="width: 350px;" 
              placeholder="请输入工作站名称"
            ></el-input>
          </el-form-item>
          
          <el-form-item label="工作站地点" class="c_item_big">
            <el-input 
              v-model="workstation.workstationLocation" 
              style="width: 350px;" 
              placeholder="请输入工作站地点"
            ></el-input>
          </el-form-item>
          
          <el-form-item label="所在车间名称" class="c_item_big">
            <el-select 
              placeholder="请选择车间" 
              v-model="workstation.workshopId" 
              style="width: 350px;"
            >
              <el-option 
                v-for="intm in Workshop" 
                :key="intm.workshopcId"
                :value="intm.workshopcId" 
                :label="intm.workshopName"
              ></el-option>
            </el-select>
          </el-form-item>

          <div style="display: flex; width: 100%;">
            <el-form-item label="所属工序" class="c_item">
              <el-select 
                placeholder="请选择工序" 
                v-model="workstation.processId" 
                style="width: 150px;"
              >
                <el-option 
                  v-for="intm in Process" 
                  :key="intm.processId"
                  :value="intm.processId" 
                  :label="intm.processName"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="是否启用" class="c_item">
              <el-radio-group v-model="workstation.isEnabled">
                <el-radio label="是" value="0">是</el-radio>
                <el-radio label="否" value="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <el-form-item label="备注" class="c_item_big">
            <el-input 
              v-model="workstation.remark" 
              style="width: 350px;" 
              placeholder="请输入备注"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="onSubmit" class="right-bottom">添加</el-button>
          </el-form-item>
        </el-form>
      </template>
    </el-card>
    
    <router-view/>
  </div>
</template>

<style scoped>
.c_item {
  flex: 1;
  margin: 0px 5px 15px 0;
  width: calc((100% - 10px) / 2);
  min-width: calc((100% - 10px) / 2);
  max-width: calc((100% - 10px) / 2);
}

.c_item_big {
  flex: 2;
  margin: 0px 5px 15px 0;
  width: calc((100% - 10px) / 1);
  min-width: calc((100% - 10px) / 1);
  max-width: calc((100% - 10px) / 1);
}

.card_wrap {
  width: 98%;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.color {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.right-bottom {
  margin-top: 10px;
  margin-left: 700px;
}

.right-bottom2 {
  margin-top: 20px;
  margin-left: 850px;
}
</style>